<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 * @author   howe <howe1995@163.com>
 */

namespace App\Middleware;

use App\Constant\ApiCodeEnum;
use App\Support\Traits\ServiceException;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface as HttpResponse;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;

/**
 * Http Token 授权验证中间件.
 */
class JWTAuthMiddleware implements MiddlewareInterface
{
    use ServiceException;

    /**
     * @var RequestInterface
     */
    protected $request;

    /**
     * @var HttpResponse
     */
    protected $response;

    /**
     * 授权验证守卫.
     *
     * @var string
     */
    private $guard = 'jwt';

    public function __construct(HttpResponse $response, RequestInterface $request)
    {
        $this->response = $response;
        $this->request = $request;
    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $token = str_replace('Bearer ', '', $request->getHeader('Authorization'));
        if (! $token) {
            $this->throwBusinessException(ApiCodeEnum::CLIENT_TOKEN_UNAVAILABLE);
        }

        if (auth($this->guard)->guest()) {
            $this->throwBusinessException(ApiCodeEnum::CLIENT_HTTP_UNAUTHORIZED_EXPIRED);
        }

        return $handler->handle($request);
    }
}
